<?php
if (!defined("MCTDESIGN")) die("#");
if ($act=="delcart") {
		if (!empty($proid)) {
			$cart_session_new = "";
			unset($carts);
			$carts = explode("**",$cart_session);
			$total_price = 0;
			for($i = 1;$i < count($carts);$i++) {
				list($pro_id, $pro_name, $pro_price)=explode("||",$carts[$i]);
				if ($proid != $pro_id) {
					$cart_session_new .= "**".$carts[$i];
				}
			}
			$_SESSION["cart_session"] = $cart_session_new;
            header("Location: GioHang.html");
		}
		else {
			header("Location: GioHang.html");
		}
		return false;
}
if(isset($_POST["updateCart"])){
		$total = isset($_POST["total"]) ? intval($_POST["total"]) : 0;
	 	unset($carts);
		$carts = explode("**",$cart_session);
		$list_cart = "";
	   	for ($i=1;$i<=$total;$i++) {
			$pro_id    = isset($_POST["pro_id_$i"])    ? intval($_POST["pro_id_$i"])    : 0;
			$pro_count = isset($_POST["pro_count_$i"]) ? intval($_POST["pro_count_$i"]) : 0;
			list($proid, $pro_name, $pro_price, $procount)=explode("||",$carts[$i]);
			$list_cart .= "**".$proid."||".$pro_name."||".$pro_price."||".$pro_count."";
		}
		$_SESSION["cart_session"] = $list_cart;
		echo "<script>window.location=\"GioHang.html\";</script>";
		return false;
}

function send_ddh_to_email($admin_email,$from,$hoten,$dchi,$dthoai,$email,$htthanhtoan,$dc_nhan,$gchu,$arr_sp,$tongtien){
    $header = "Content-type: text/html; charset=utf-8\r\nFrom: $from\r\nReply-to: $from";
    $to = $admin_email;
    $subject = "Don hang moi | ".gmdates(time())." ";
    $mess = "";
    $mess .= "<div style=\"width: 100%;height: 25px;background: green; text-align: center;color: #ffffff;\"><strong>Thông tin khách hàng</strong></div>\n"; 
    $mess .= "<ul style=\"padding-left: 25px;position: relative;\">\n"; 
    $mess .= "    <li style=\"padding-top: 3px;\">Họ tên: <strong> $hoten</strong></li>\n"; 
    $mess .= "    <li style=\"padding-top: 3px;\">Địa chỉ: <strong> $dchi</strong></li>\n"; 
    $mess .= "    <li style=\"padding-top: 3px;\">Điện thoại: <strong> $dthoai</strong></li>\n"; 
    $mess .= "    <li style=\"padding-top: 3px;\">Email: <strong> $email</strong></li>\n"; 
    $mess .= "    <li style=\"padding-top: 3px;\">Hình thức thanh toán: <strong> $htthanhtoan</strong></li>\n"; 
    $mess .= "    <li style=\"padding-top: 3px;\">Địa chỉ nhận hàng: <strong> $dc_nhan</strong></li>\n"; 
    $mess .= "    <li style=\"padding-top: 3px;\">Ghi chú: <strong> $gchu</strong></li>\n"; 
    $mess .= "</ul>\n"; 
    $mess .= "<div style=\"width: 100%;height: 25px;background: green; text-align: center;color: #ffffff;\"><strong>Thông tin đơn hàng</strong></div>\n"; 
    $mess .= "<table style=\"width: 100%; border: 1px solid #999999\">\n"; 
    $mess .= "    <tr style=\"background: #cccccc;border: 1px solid #CCCCCC;\">\n"; 
    $mess .= "        <td style=\"width: 50%; text-align: center;\"><b>Tên sản phẩm</b></td>\n"; 
    $mess .= "        <td style=\"width: 15%; text-align: center;\"><b>Số lượng</b></td>\n"; 
    $mess .= "        <td style=\"width: 15%; text-align: center;\"><b>Giá bán</b></td>\n"; 
    $mess .= "        <td style=\"width: 20%; text-align: center;\"><b>Thành tiền</b></td>\n"; 
    $mess .= "    </tr>\n"; 
    foreach($arr_sp as $k=>$v){
        $mess .="    <tr style=\"background: #f7f7f7;border:1px solid #CCCCCC;\">\n"; 
        $mess .="        <td style=\"width: 50%; text-align: center;padding-top: 5px;\">".$v['tensp']."</td>\n"; 
        $mess .="        <td style=\"width: 15%; text-align: center;\">".$v['sluong']."</td>\n"; 
        $mess .="        <td style=\"width: 15%; text-align: center;\">".$v['gia']."</td>\n"; 
        $mess .="        <td style=\"width: 20%; text-align: center;\">".$v['thanhtien']."</td>\n"; 
        $mess .="    </tr>\n"; 
        $mess .="    \n";
    }
    $mess .= "    <tr style=\"border: 1px solid #CCCCCC;\">\n"; 
    $mess .= "        <td colspan=\"2\"></td>\n"; 
    $mess .= "        <td colspan=\"2\" style=\"text-align: center;color: red; padding-top: 10px;\">Tổng tiền: <strong>$tongtien vnd</strong></td>\n"; 
    $mess .= "    </tr>\n"; 
    $mess .= "</table>\n"; 
    $mess .= "<div style=\"margin-top: 10px;\">\n"; 
    $mess .= "    Đơn hàng được tạo vào: ".gmdates(time())."\n"; 
    $mess .= "</div>\n";
    // send mail
    if(mail($to,$subject,$mess,$header)){
        return true;
    }else{
        return false;
    }    
}
$temp->assign( 'base_tpl', "".$dir_tpl."" );
if ($cart_count>0) {
			unset($carts);
			$carts = explode("**",$cart_session);
			$total_price = 0;
			$carts_count = count($carts);
			# Send Order
			if(isset($_POST["butSend"])){
				$security_s = isset($_POST["security_s"]) ? intval(stripslashes($_POST["security_s"])) : 0;
				$txtHoten = isset($_POST["txtHoten"]) ? fixquotes(stripslashes($_POST["txtHoten"])) : "";
				$txtCompany = isset($_POST["txtCompany"]) ? fixquotes(stripslashes($_POST["txtCompany"])) : "";
				$txtdiachi = isset($_POST["txtdiachi"]) ? fixquotes(stripslashes($_POST["txtdiachi"])) : "";
				$txtdienthoai = isset($_POST["txtdienthoai"]) ? fixquotes(stripslashes($_POST["txtdienthoai"])) : "";
				$txtEmail = isset($_POST["txtEmail"]) ? fixquotes(stripslashes($_POST["txtEmail"])) : "";
				$ddSoluong = isset($_POST["ddSoluong"]) ? intval(stripslashes($_POST["ddSoluong"])) : "";
				$txtPayment = isset($_POST["txtPayment"]) ? fixquotes(stripslashes($_POST["txtPayment"])) : "";
				$txtShipAddress = isset($_POST["txtShipAddress"]) ? fixquotes(stripslashes($_POST["txtShipAddress"])) : "";
				$txtGhichu = isset($_POST["txtGhichu"]) ? fixquotes(stripslashes($_POST["txtGhichu"])) : "";
				$txtCode = isset($_POST["txtCode"]) ? intval(stripslashes($_POST["txtCode"])) : 0;
                $txtCMND = isset($_POST['txtCMND']) ? intval($_POST['txtCMND']) : "";
                
				if (empty($txtHoten)) {
					$temp->assign( 'error_order', "Bạn chưa nhập họ tên." );
				}
				else if (empty($txtdiachi) ) {
					$temp->assign( 'error_order', "Bạn chưa nhập dại chỉ của bạn." );
				}
                else if(empty($txtCMND) || !intval($txtCMND)){
                    $temp->assign( 'error_order', "Bạn chưa nhập số chứng minh nhân dân." );
                }
                else if(!intval($txtCMND)){
                    $temp->assign( 'error_order', "Chứng minh nhân dân phải là số." );
                }
				else if (empty($txtdienthoai) ) {
					$temp->assign( 'error_order', "Bạn chưa nhập số điện thoại của bạn." );
				}
				else if (empty($txtEmail) ) {
					$temp->assign( 'error_order', "Bạn chưa nhập địa chỉ email của bạn." );
				}
				else if ($txtCode!=$security_s) {
					$temp->assign( 'error_order', "Mã xác nhận kô chính xác." );
				}
				else {		    
				/* Email Admin */
				$shop_mail = get_data('shop_mail','config_values');
					$to = $shop_mail;
					$from = trim($txtEmail);
                    if (empty($user_id)) {
                        $ngaydathang = time();
						$mysql->query("INSERT INTO ".$tb_fix."_customer (cus_email, cus_fullname, cus_address, cus_cmnd, cus_tel, cus_mobile,  cus_date) VALUES ('".$txtEmail."','".$txtHoten."','".$txtdiachi."','".$txtCMND."','".$txtdienthoai."','".$txtdienthoai."', '".$cus_date."')");
                        $cus_id = $mysql->insert_id();
                        
                        $tendh=name_don_hang() + 1;
                        // insert don hang
                        $sql = "insert into ".$tb_fix."_don_hang(dha_id,dha_ten_dh,dha_ngay_tao,cus_id)
                                    values (0,'$tendh',$ngaydathang,$cus_id)";
                        $mysql->query($sql);
                        $donhangid=$mysql->insert_id();
                        // insert thanh toan don hang
                        $sql = "insert into ".$tb_fix."_thanh_toan_dh values(0,'$txtPayment','$txtShipAddress','$txtGhichu',$donhangid)";
                        $mysql->query($sql);
                                    
					}
					for($i = 1;$i < $carts_count;$i++) {
						$c++;
						list($pro_id, $pro_name, $pro_price, $pro_count)=explode("||",$carts[$i]);
						$pro_count = intval($pro_count);
						if (empty($pro_count)) $pro_count = 1;
						$pro_price_ok = $pro_price*$pro_count;
						$total_price = $total_price+$pro_price_ok;
						$price = number_format($pro_price_ok, 0, '.', '.');
						$pro_price  = number_format($pro_price, 0, '.', '.');
                        $arr_pro[$i]['tensp'] = $pro_name;
                        $arr_pro[$i]['sluong'] = $pro_count;
                        $arr_pro[$i]['gia'] = $pro_price;
                        $arr_pro[$i]['thanhtien'] = $price;
						//$message .= "\n * Tên sản phẩm: ".$pro_name." || Số lượng : $pro_count || Giá bán : ".$pro_price." VNĐ || Thành tiền : ".$price." VNĐ \n";
                        //insert chi tiet don hang
                        $sql = "insert into ".$tb_fix."_chi_tiet_dh
                                    values(0,$donhangid,$pro_id,$pro_count,$pro_price_ok)";  
                                    
                        $mysql->query($sql);                                  
					}					
                    //insert tong tien don hang
                    $sql = "update ".$tb_fix."_don_hang 
                                    set dha_tong_tien = $total_price
                                    where dha_id = $donhangid
                                    ";
                    $mysql->query($sql);
					$total_price  = number_format($total_price, 0, '.', '.');
					if(!send_ddh_to_email($shop_mail,$from,$txtHoten,$txtdiachi,$txtdienthoai,$txtEmail,$txtPayment,$txtShipAddress,$txtGhichu,$arr_pro,$total_price)){
                        echo "<script>alert('không gửi được đơn hàng!');</script>";
                    }
					$_SESSION["cart_session"] = "";
					echo "<script>location='$cus_id-Don-Hang-Da-Hoan-Thanh.html';</script>";
					return false;
				}
			}
			# End Send Order
            // SAN PHAM TRONG GIO HANG
			if ($carts_count>0) 
			{
				$security=rand(111111,142354);
				$temp->assign( 'security', "".$security."" );
               

				$list_cart = "<form action=\"\" method=\"post\" name=\"cart\" id=\"form-cart\" style=\"clear: both;\">";
				$list_cart .= "<table align=\"center\" bgcolor=\"#b2b3b5\" border=\"0\" cellpadding=\"4\" cellspacing=\"1\" width=\"581\">
								<tr bgcolor=\"#cccccc\">
									<td width=\"30\" align=\"center\"><strong>Xóa</strong></td>
									<td align=\"center\"><strong>Tên sản phẩm</strong> </td>
									<td width=\"90\" align=\"center\"><strong>Số lượng </strong></td>
									<td width=\"90\" align=\"center\"><strong>Giá bán </strong></td>
									<td width=\"100\" align=\"center\"><strong>Thành tiền</strong> </td>
				            	</tr>";
				$c = 0;
				for($i = 1;$i < $carts_count;$i++) {
					$c++;
					list($pro_id, $pro_name, $pro_price, $pro_count)=explode("||",$carts[$i]);
					$pro_count = intval($pro_count);
					if (empty($pro_count)) $pro_count = 1;
					$pro_price_ok = $pro_price*$pro_count;
					$total_price = $total_price+$pro_price_ok;
					$price = number_format($pro_price_ok, 0, '.', '.');
					$pro_price  = number_format($pro_price, 0, '.', '.');
					$list_cart .= "<tr bgcolor=\"#ffffff\">
									<td width=\"30\" align=\"center\">
										<a href=\"Delete-Product-".$pro_id.".html\"><img style=\"cursor: pointer;\"\ src=\"_images/delete.gif\" width=\"15\" border=\"0\" height=\"15\"></a>
									</td>
									<td>$pro_name</td>
									<td width=\"90\" align=\"center\">
									<input name='pro_id_".$c."' type='hidden' value='".$pro_id."'> <input name='pro_count_".$c."' maxlength=\"2\" type='text' size='3' maxlength='15' value='".$pro_count."'>";
					$list_cart .= "	</td>
									<td width=\"90\" align=\"center\">$pro_price VNĐ</td>
									<td width=\"120\" align=\"center\">$price VNĐ</td>
								</tr>
					";
				}
				$total_price = number_format($total_price, 0, '.', '.');
				$list_cart .= "<tr bgcolor=\"#ffffff\">
			              			<td colspan=\"2\">&nbsp;</td>
                                    <td align=\"center\"><input type='button' value='Cập nhật' onclick='cart.submit();' style='background: #E77843; border:1px solid #FF8E01; color:#ffffff;cursor: pointer' /></td>
			              			<td align=\"center\"><font color=\"blue\">Tổng cộng </font></td>
									<td class=\"redText\" align=\"center\"><strong><font color=\"red\">$total_price VNĐ</font></strong></td>
								</tr>
					";
				$list_cart .= "</table><input type='hidden' name='total' value='".$c."'><input type='hidden' name='updateCart' value='updateCart'>";
				$list_cart .= "</form>";
			}
	}
	else $list_cart = msg_Error("<br>Chưa có sản phẩm nào trong giỏ hàng.");
	$temp->assign( 'list_productcart', $list_cart );
	$temp->assign( 'cart_session', $cart_session );
	$content = $temp->fetch( 'product/_shopcart.mct' );


?>